/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.p2psimulator.entity.overlaynetwork.routingtable;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.p2psimulator.entity.Id;

/**
 *
 * @author amorim
 */
public class SuperpeerRoutingTable extends FloodRoutingTable {

    private boolean superpeer;
    private Map<Id, Set<Id>> leavesMap;
    private Set<Id> neighbors;
    private int maxNeighbors;

    public SuperpeerRoutingTable(int maxSize) {
        this.superpeer = false;
        this.leavesMap = new HashMap<Id, Set<Id>>();
        this.neighbors = new HashSet<Id>();
        this.maxNeighbors = maxSize;
    }

    public void addLeaf(Id idpeer){
        if (!this.leavesMap.containsKey(idpeer))
            this.leavesMap.put(idpeer, new HashSet<Id>());
    }
    
    @Override
    public void insertNeighbor(Id peer) {
        
        if (this.neighbors.size() < maxNeighbors) {
            this.neighbors.add(peer);
        }
    }

    @Override
    public boolean contains(Id peer) {
        return this.neighbors.contains(peer);
    }

    @Override
    public boolean deletePeer(Id peer) {
        if (this.neighbors.contains(peer)) {
            this.neighbors.contains(peer);
            return true;
        }
        return false;
    }

    @Override
    public void clear() {
        this.neighbors.clear();
    }

    public Id containsFile(Id fileId) {
        if (superpeer) {
            for (Id id : this.leavesMap.keySet()) {

                Set<Id> set = this.leavesMap.get(id);
                if (set.contains(fileId)) {
                    return id;
                }
            }
        }
        return null;
    }

    public boolean addFileId(Id peer, Id fileId) {
        if (superpeer) {
            if (this.leavesMap.containsKey(peer)) {
                this.leavesMap.get(peer).add(fileId);
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    public Map<Id, Set<Id>> getLeavesMap() {
        return leavesMap;
    }

    public boolean isSuperpeer() {
        return superpeer;
    }

    public void setSuperpeer(boolean superpeer) {
        this.superpeer = superpeer;
    }

    public synchronized Set<Id> getNeighbors() {
        return neighbors;
    }

    public int getMaxNeighbors() {
        return maxNeighbors;
    }
    
    public synchronized int size(){
        return this.neighbors.size();
    }
    
}
